/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { message } from 'antd';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, { ModalForm } from '@ant-design/pro-form';
import React, { useRef, useState, useEffect } from 'react';
import { addRegionAdmin } from '@/services/YzBond';
import KbAddressSelect from '../KbAddressSelect';

interface KbEdit {
  getDetail: () => void;
  onChange?: (value: any) => void;
  children: React.ReactNode;
  modifyId?: string;
  value?: any;
}

const KbEditForm: React.FC<KbEdit> = (props) => {
  const { children, modifyId, value, getDetail } = props;
  const formRef = useRef<ProFormInstance>();
  const [visible, setVisible] = useState<boolean>(false);
  const [seleceValue, setSeleceValue] = useState<(string | number)[]>([]);
  const [selectOptions, setSelectOptions] = useState<Record<string, string>[][]>([]);

  const onSelectChange = (values: (string | number)[], options: Record<string, string>[][]) => {
    setSeleceValue(values);
    setSelectOptions(options);
  };

  const formatCompanyAddress = (addressCity: string[][]) => {
    const str = addressCity[0][0] + addressCity[0][1];
    return str + '(' + addressCity.map((item) => item[2]).join('、') + ')';
  };

  const onFinish = async (values: any) => {
    const { address: addressCity, ...rest } = values;
    const addressCode: string[][] = selectOptions.map((item) => {
      return item.map((item1) => item1.value);
    });
    const addressName: string[][] = selectOptions.map((item) => {
      return item.map((item1) => item1.label);
    });
    const district = addressCode.map((item) => item.slice(2, 3)).flat(Infinity);
    const address = addressCode[0].splice(0, 2);
    const params = {
      ...rest,
      id: modifyId,
      address: JSON.stringify(address),
      district: JSON.stringify(district),
      addressName: formatCompanyAddress(addressName),
    };
    const { code, msg } = await addRegionAdmin(params);
    if (code == 0) {
      getDetail();
      message.success(msg);
      setVisible(false);
    } else {
      message.error(msg);
    }
  };

  useEffect(() => {
    if (visible) setSeleceValue(value);
  }, [visible]);

  return (
    <>
      <div onClick={() => setVisible(true)}>
        <a>{children}</a>
      </div>
      <ModalForm
        title='请选择省市区'
        formRef={formRef}
        layout='horizontal'
        visible={visible}
        onFinish={onFinish}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => setVisible(false),
        }}
      >
        <ProForm.Item label='省市区' style={{ width: '100%' }}>
          <KbAddressSelect
            level={2}
            multiple
            value={seleceValue}
            onChange={(values, options) => onSelectChange(values, options)}
          ></KbAddressSelect>
        </ProForm.Item>
      </ModalForm>
    </>
  );
};

export default KbEditForm;
